package suo;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    private Executor executor = new SimpleExecutor();

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    public <E> List<E> selectList(String statementId, Object... param) throws SQLException, InvocationTargetException, IntrospectionException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        List<E> query = executor.query(configuration, mapperStatement, param);
        return query;
    }

    public <T> T selectOne(String statementId, Object... param) throws Exception {
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        List<T> query = executor.query(configuration, mapperStatement, param);
        if (query.size() == 1) {
            return query.get(0);
        } else {
            throw new Exception("本应只有一条记录，却查到多条记录");
        }
    }

    public Integer update(String statementId, Object... param) throws NoSuchFieldException, IllegalAccessException, SQLException {
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        Integer i=executor.update(configuration,mapperStatement,param);
        return i;
    }

    public void close() throws SQLException {
        executor.close();
    }


    public <T> T getMappper(Class<?> mapperClass) {
        T o = (T) Proxy.newProxyInstance(mapperClass.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                //所属类的类名
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
                Type genericReturnType = method.getGenericReturnType();
                if ("select".equals(mapperStatement.getType())) {
                    if (genericReturnType instanceof ParameterizedType) {
                        return selectList(statementId, args);
                    }
                    return selectOne(statementId, args);
                }
                if("update".equals(mapperStatement.getType())){
                    update(statementId,args);
                }
                return null;
            }
        });

        return o;
    }
}
